package com.fone.player.airone;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

public class AirPlay {

	
	protected static String md5Digest(String input) {
        byte[] source;
        try {
                //Get byte according by specified coding.
                source = input.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
                source = input.getBytes();
        }
        String result = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(source);
                //The result should be one 128 integer
                byte temp[] = md.digest();
                char str[] = new char[16 * 2];
                int k = 0;
                for (int i = 0; i < 16; i++) {
                        byte byte0 = temp[i];
                        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                        str[k++] = hexDigits[byte0 & 0xf];
                }
                result = new String(str);
        } catch (Exception e) {
                e.printStackTrace();
        }
        return result;

}
protected static String makeAuthorization(String realm,String nonce,String method,String username, String password,  String uri) {
       
        String ha1 = md5Digest(username+":"+realm+":"+password);
        String ha2 = md5Digest(method+":"+uri);
        return md5Digest(ha1+":"+nonce+":"+ha2);
        
//        String authorization = "Digest username=\""+username+"\", "
//                +"realm=\""+realm+"\", "
//                +"nonce=\""+nonce+"\", "
//                +"uri=\""+uri+"\", "
//                +"response=\""+response+"\"";
//        return authorization;
}

public static String getResponse(String nonce,String realm,String username, String password,String uri) throws IOException {
       
       return makeAuthorization(realm,nonce,"POST",username,password,uri);
       
}

	
}
